package com.comp3111.happymeal;

import org.json.JSONException;
import org.json.JSONObject;

import com.configuration.Configuration;
import com.user.LoginRegister;

import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


/*
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	
	private int backButtonCount;
	private int attemptLoginResult;
	/**
	 * @return the attemptLoginResult
	 */
	public int getAttemptLoginResult() {
		return attemptLoginResult;
	}

	/**
	 * @param attemptLoginResult the attemptLoginResult to set
	 */
	public void setAttemptLoginResult(int attemptLoginResult) {
		this.attemptLoginResult = attemptLoginResult;
	}

	final int BLOCKED_USER = 0;
	final int NEXT = 1;
	final int REQUEST_DENIED = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login_page);
		
		//Initialize back button count for handling app quit
		backButtonCount = 0;
		
		// Set up the login form.
		final EditText et_login_page_telephone = (EditText)findViewById(R.id.login_page_telephone);
		Button btn_login_page_next = (Button)findViewById(R.id.login_page_next);
		
		//Configure the next button
		btn_login_page_next.setOnClickListener	(new OnClickListener(){
			public void onClick(View v){
				/*
				 * Bug : Crash when nothing entered
				 * TODO:
				 * write a test here to check if the user entered something
				 */
				
				final String telephone = et_login_page_telephone.getText().toString();
				
				if(!checkNumber(telephone)){
					
					if(Configuration.showLog){
						Log.d("LoginActivity","btn_login_page_next");
					}
					
					wrongNumberAlert();
					return;
				}
				
				//Initialize attemptLoginResult
				attemptLoginResult = -1;
				
				//Start a new thread to attempt Login (requirement when connecting online)
				Thread attemptThread = new Thread(new Runnable(){  
		            
		            public void run(){
		            	attemptLoginResult = attemptLogin(telephone);
		            }

		        });  
		        attemptThread.start();
		        
		        while(attemptThread.isAlive()){
		        	//Waiting to get server response
		        }
		        
			    
		        if(attemptLoginResult == NEXT){
					// Jump to next intent
					Intent intentPass = new Intent(LoginActivity.this, LoginTypeSmsActivity.class);
					
					//Pass telephone intent
					intentPass.putExtra("TELEPHONE",telephone.trim());
					
					//Go to next page
					startActivity(intentPass);
					finish();
				}else if(attemptLoginResult==BLOCKED_USER){
					Toast.makeText(LoginActivity.this,"The phone number your have entered is being blocked.", Toast.LENGTH_LONG).show();
				}else if(attemptLoginResult==REQUEST_DENIED){
					Toast.makeText(LoginActivity.this,"Your login/register request is being deined.", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(LoginActivity.this,"Please check your network connection status.", Toast.LENGTH_LONG).show();
				}
			}
		});
		
	}
	
	/*
	 * The app will be killed when pressed the back button
	 * Override the back button to prevent jumping back to LoadingScreenActivity
	 */
	public void onBackPressed(){
		if(Configuration.showLog){
			Log.d("LoginActivity", "onBackPressed");
		}
			
        if(backButtonCount >= 1){
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }else{
            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
            backButtonCount++;
        }
    }
	
	
	/*
	 * checkNumber checks whether the entered phone number is a valid Hong Kong mobile number
	 * Valid Definition
	 * 5000-0000 ~ 6999-9999
	 * 8000-0000 ~ 9989-9999
	 */
	private boolean checkNumber(String telephone){
		int telephone_int = Integer.parseInt(telephone);
		
		if(telephone == ""){
			return false;
		}
		
		if((telephone_int > 50000000 && telephone_int<69999999) || (telephone_int>80000000 && telephone_int<99899999)){
			return true;
		}else{
			return false;
		}
	}
	
	
	/*
	 * wrongNumberAlert prompt out a dialog asking for entering a valid mobile number 
	 */
	private void wrongNumberAlert(){
		AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
		dialog.setTitle("Invalid Mobile Number");
		//dialog.setIcon(android.R.drawable.ic_dialog_alert);
		dialog.setMessage("Please enter a valid mobile phone number");
		dialog.setCancelable(false);
		dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {  
		    public void onClick(DialogInterface dialog, int which) {  
		    	//
		    }  
		});
		dialog.show();
	}
	
	/*
	 * attemptLogin tries to login/register with the entered phone number
	 * It handles several messages returned by the server and return an integer
	 * Messages
	 * - NEXT				: request successfully handled by the server and 
	 * 						  proceed to the next step
	 * - BLOCKED_USER		: phone number being blocked
	 * - REQUEST_DENIED		: unable to POST telephone and imei
	 * 
	 * Return Values
	 * - 0 : BLOCKED_USER
	 * - 1 : NEXT
	 * - 2 : REQUEST_DENIED
	 */
	private int attemptLogin(String telephone){
		
		final String KEY_BLOCKED_USER	= "BLOCKED_USER";
		final String KEY_NEXT 			= "NEXT";
		final String KEY_REQUEST_DENIED = "REQUEST_DENIED";
		final String KEY_MESSAGE 		= "MESSAGE";
		
		LoginRegister loginRegister = new LoginRegister();
		JSONObject result = loginRegister.loginRegisterUser(telephone,LoginActivity.this);
		
		try {
			//Log.d("test","test");
			if(result.getString(KEY_MESSAGE)!= null){
				if(Configuration.showLog){
					Log.d("LoginActivity","KEY_MESSAGE = " + result.getString(KEY_MESSAGE));
				}
				if(result.getString(KEY_MESSAGE).equalsIgnoreCase(KEY_BLOCKED_USER)){
					return BLOCKED_USER;
				}else if(result.getString(KEY_MESSAGE).equalsIgnoreCase(KEY_NEXT)){
					return NEXT;
				}else{
					return REQUEST_DENIED;
				}
			}else{
				if(Configuration.showLog){
					Log.d("LoginActivity Error","attemptLogin null reply");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("LoginActivity Error","attemptLogin Exception");
			}
		}
		
		return REQUEST_DENIED;
	}
	
}
